package com.gbq.controller;

import com.gbq.constants.BaseConstants;
import com.gbq.service.BaseService;
import com.gbq.task.Task;
import com.gbq.utils.BaseUtils;
import com.gbq.utils.FTPUtil;
import com.gbq.vo.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.netflix.discovery.converters.Auto;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import sun.net.ftp.FtpClient;


import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;

@Slf4j
@RestController
public class Controller {

    private static final Gson gson=new GsonBuilder().disableHtmlEscaping().create();


    @Autowired
    private BaseService baseService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private Task task;
    @RequestMapping("/test")
    public void test(@RequestParam("card") String card){

        System.out.println(card);
        JSONObject object = baseService.selectPersonByCardno(card);

        System.out.println(object.get("warntype"));
    }



    @RequestMapping("/person")
    public Object person(@RequestBody RequestPerson requestPerson){

          log.info(requestPerson.toString());

          //初始化参数
          BaseConstants baseConstants = new BaseConstants();
          Map<String,String> baseMap =  baseConstants.getMap();
          Map<String,String> verifyResultMap =  baseConstants.getVerifyResultMap();
          Map<String,Object> maplist = new HashMap<String,Object>();
          Map<String,Object> map = new HashMap<String,Object>();
          List<RequestPerson> list = new ArrayList<>();
          Boolean result = true;


          String deviceid = baseService.selectBySn(requestPerson.getPassNo());   //根据设备SN获取device表中的id
        //组装kafka数据
        //将性别民族和验证结果编码转换成文字
          requestPerson.setDeviceId(deviceid);
          requestPerson.setGender(baseMap.get(requestPerson.getGenderCode()));    //转换性别
          requestPerson.setNation(baseMap.get(requestPerson.getNationCode()));    //转换民族
          requestPerson.setVerifyResultCode(requestPerson.getVerifyResult());
          requestPerson.setVerifyResult(verifyResultMap.get(requestPerson.getVerifyResult()));    //转换验证结果

          requestPerson.setId(UUID.randomUUID().toString());



          //判断是否之前有传输失败的数据
          log.info("缓存数据个数:"+BaseConstants.list.size());
          if (BaseConstants.list.size()>0){
               BaseConstants.list.add(requestPerson);
               maplist.put("data",BaseConstants.list);
               map.put("Person_Origin",maplist);
          }else {
              list.add(requestPerson);
              maplist.put("data",list);
              map.put("Person_Origin",maplist);
          }

          result = task.postPersonList(map);

          if (result){
              log.info(""+map);
              BaseConstants.list.clear();   //清空缓存中的list
          }else {
              if (BaseConstants.list.size()==0){           //如果首次发送失败
                  BaseConstants.list.add(requestPerson);  //如果发送post请求失败，则放入缓存
              }
              log.info("post请求失败");
          }

        return result;

    }

    @RequestMapping("/blacklist")
    public Object blacklist(@RequestBody RequestBlackPerson obj){

        log.info("I am producer01");
        System.out.println(obj);
        Map<String,String> map = new HashMap<String,String>();
        JSONObject object = baseService.selectPersonByCardno(obj.getCardNo());
        if(object.isNullObject()){
            map.put("isBlackList","0");
            map.put("status","0");
            map.put("jobId",obj.getJobId());
        }else{

            map.put("extendInfo1",""+object.get("warntype"));
            map.put("isBlackList","1");
            map.put("status","0");
            map.put("jobId",obj.getJobId());
        }

        System.out.println(map);
        return map;
    }

////FTP版本
//    @RequestMapping("/fileupload")
//    public Object fileupload(@RequestParam("filename") MultipartFile file){
//        FTPUtil ftpUtil = new FTPUtil();
//        Map<String,Object> map = new HashMap<String,Object>();
//        String org = "org";
//        Long date = new Date().getTime();   //获取时间戳
//        Integer random = (int)(Math.random()*1000+1000);    //生成随机数
//        String filename = file.getOriginalFilename();
//        String path = null;
//
//
//        String randomfilename = ""+date+random;   //将文件名变成时间戳加四位随机数
//        log.info(randomfilename);
//
//
//        try {
//            file.transferTo(new File("c:/zp"+randomfilename+".jpg"));
//        } catch (IOException e) {
//            e.printStackTrace();
//            map.put("status",-1);
//        }
//
//
//        File tempfile = new File("c:/zp"+randomfilename+".jpg");
//        randomfilename = tempfile.getName();
//
//
////上传到ftp服务器
//
//        if (filename.indexOf(org)!=-1){     //采集照片
//            try {
//                ftpUtil.connect("IMAGES/Face", "192.168.10.213", 21, "FTP_HD", "12345602");
//                ftpUtil.upload("c:/",randomfilename);
//                map.put("status",0);
//            } catch (Exception e) {
//                e.printStackTrace();
//                map.put("status",-1);
//            }
//            path = "http://192.168.10.213:8088/IMAGES/Face/" + randomfilename;
//        }else{                              //人证照片
//            try {
//                ftpUtil.connect("IMAGES/Card", "192.168.10.213", 21, "FTP_HD", "12345602");
//                ftpUtil.upload("c:/",randomfilename);
//                map.put("status",0);
//            } catch (Exception e) {
//                e.printStackTrace();
//                map.put("status",-1);
//            }
//            path = "http://192.168.10.213:8088/IMAGES/Card/" + randomfilename;
//        }
//
//
//
////清理程序临时数据
//
//        tempfile.delete();
//        ftpUtil.stop();
//        map.put("FilePath",path);
//        log.info(""+map);
//        return map;
//    }

//HTTP版本
    @RequestMapping("/fileupload")
    public Object fileupload(@RequestParam("filename") MultipartFile file) {

        Map<String,Object> map = new HashMap<String,Object>();
        String path = null;
        Boolean result = true;
        Long date = new Date().getTime();   //获取时间戳
        Integer random = (int)(Math.random()*1000+1000);    //生成随机数
        String randomfilename = ""+date+random;   //将文件名变成时间戳加四位随机数
        log.info(randomfilename);

        try {
            file.transferTo(new File("/tempImages/"+randomfilename+".jpg"));  //在本地生成临时文件
        } catch (IOException e) {
            e.printStackTrace();
            log.info("生成临时文件失败");
            map.put("status",-1);
        }

        File newfile = new File("/tempImages/"+randomfilename+".jpg");
        randomfilename = newfile.getName();    //获取上传文件的名字
        path = newfile.getPath();

        result = task.postPicture(path);    //向服务器传文件


        if (result){
            newfile.delete();
//            File fileList = new File("/tempImages");
            File fileList = new File("/tempImages");
            String[] children = fileList.list();
            if (children.length>0){
                for (String child:children){
                    System.out.println(child);
                    File tempfile = new File("/tempImages/"+child);
                    if (task.postPicture("/tempImages/"+child)){
                        tempfile.delete();
                    }
                    else {
                        break;
                    }
                }
            }

        }else {
            log.info("上传失败");
        }
        map.put("status",0);
        map.put("FilePath",randomfilename);
        return map;

    }


}
